package com.heima.media.filter;

import com.heima.media.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /**
    * 过滤器的执行逻辑
     * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1.判断当前的请求是否为登录请求，如果是直接放行  //判断是否需要鉴权
        // 获取请求url
        String path = request.getURI().getPath();  //   -->/login/in
        if (path.contains("/login")){
            // 直接放行
            return chain.filter(exchange);
        }
        // 2.判断token
        // 2.1先判断请求头中是否有token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); //返回给浏览器
        }
        // 2.2判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int status = AppJwtUtil.verifyToken(claimsBody);
        // -1:有效， 0：有效
        if (status == 0 || status == -1){
            // 解析成功，token有效，获取当前token中用户id,将userId和name放入到请求头中转发到后端的微服务，放行
            Integer userId = claimsBody.get("userId",Integer.class);
            String name = claimsBody.get("name",String.class);
            request.mutate().header("userId",userId.toString());
            request.mutate().header("name",name);
            // 继续进入到后面的微服务中
            return chain.filter(exchange);
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
